﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

namespace SmartMusicBox.Framework.Helper
{
    public static class WebRequestHelper
    {
        private static RequestInfo CreateRequestInfo(string uriString,  Action<string> failed)
        {
            var request = (HttpWebRequest)WebRequest.Create(new Uri(uriString));
            return new RequestInfo
            {
                Request = request,
                Failed = failed
            };
        }

        private static void OnGetResponseCompleted(IAsyncResult ar)
        {
            var asyncState = (RequestInfo)ar.AsyncState;
            try
            {
                var response = (HttpWebResponse)asyncState.Request.EndGetResponse(ar);
                if (!asyncState.Cancelled)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        asyncState.ReceivedString(reader.ReadToEnd());
                    }
                }
                return;
            }
            catch (Exception ex)
            {
                asyncState.Failed(ex.Message);
            }
        }

        public static RequestInfo SendStringRequest(string uriString, Action<string> received, Action<string> failed)
        {
            var info = CreateRequestInfo(uriString, failed);
            info.ReceivedString = received;
            info.BeginGetResponse();
            return info;
        }

        public class RequestInfo
        {
            public bool Cancelled;
            public Action<string> Failed;
            public Action<string> ReceivedString;
            public HttpWebRequest Request;

            public void BeginGetResponse()
            {
                Request.BeginGetResponse(OnGetResponseCompleted, this);
            }
        }
    }
}
